package com.spring.hx.controller;

import com.alibaba.fastjson.JSONObject;
import com.spring.hx.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import com.spring.hx.service.UserService;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.core.userdetails.UserDetails;
//import java.util.Collection;
//import java.util.Optional;

/**
 * 用户相关接口
 */
@RestController
@RefreshScope
@RequestMapping("users")
public class UserController {

	private static final Logger log = LoggerFactory.getLogger(UserController.class);
	private UserService userService;

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@PostMapping("login")
	public Result login(@RequestBody JSONObject loginParams){
		String nickname = loginParams.getString("name");
		String pwd = loginParams.getString("pwd");
		String tel = loginParams.getString("tel");
		try {
			return Result.ofNullable(userService.login(nickname, tel, pwd));
		}catch (Exception e) {
			e.printStackTrace();
			return Result.error(500,"登陆异常");
		}
	}


	@GetMapping("bonus-logs")
	public Result getBonusLogs(){
		return Result.ofNullable(userService.bonus());
	}

	@GetMapping( "/{id}")
	public Result getId(@PathVariable(value = "id") long id) {
		
		return Result.ofNullable(userService.getById(id));
	}

//	@GetMapping("/{id}")
//	public Optional<User> findById(@PathVariable Long id) {
//		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//		if (principal instanceof UserDetails) {
//			UserDetails user = (UserDetails) principal;
//			Collection<? extends GrantedAuthority> collection = user.getAuthorities();
//			for (GrantedAuthority c : collection) {
//				// 打印当前登录用户的信息
//				log.info("当前用户是{}，角色是{}", user.getUsername(), c.getAuthority());
//			}
//		} else {
//			// do other things
//		}
//		return this.userRepository.findById(id);
//	}
}
